今天會針對JavaScript的Class的繼承語法進行解釋
首先Constructor prototype繼承可以透過Class的extends關鍵字達成
舉例:
class Name{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
intro(){
console.log(this.firstName + ' 今年' + this.age + '歲')
}
}
class Student extends Name{
constructor(major, grade, firstName, lastName, age){
super(firstName, lastName, age)
this.major = major;
this.grade = grade;
}
study(){
console.log('學生' + this.firstName + '的' + this.major + '很厲害');
}
}
let jeremy = new Student('chemistry', 3.5, 'jeremy', 'hung', 27)
jeremy.study(); //學生jeremy的chemistry很厲害
解釋部分可分為
class Student extends Name{
// Student class的Parameter包含(major, grade, firstName, lastName以及age)
constructor(major, grade, firstName, lastName, age){
//使用super關鍵字呼叫父Class的constructor存取屬性和方法
super(firstName, lastName, age)
this.major = major;
this.grade = grade;
}
//建立study method
study(){
console.log('學生' + this.firstName + '的' + this.major + '很厲害');
}
}